<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/10/18 13:54
 * Desc: 私人定制
 */
class Service_Api_Customize extends Contract_Api_Customize
{
    /**
     * 产品类型
     */
    const TYPE_ID = 14;

    public function plan($params): array
    {
        /**
         * @var $page
         * @var $pagesize
         */
        extract($params);

        $offset = St_Page::offset($page, $pagesize);

        $builder = DB::select('id', 'title', 'litpic', 'days')
            ->from('customize_plan');

        $total = $builder->execute()->count();

        $list = $builder->order_by('displayorder', 'asc')
            ->order_by('modtime', 'desc')
            ->order_by('addtime', 'desc')
            ->offset($offset)
            ->limit($pagesize)
            ->execute()
            ->as_array();
        foreach ($list as &$item) {
            $item['litpic'] = $this->img_url($item['litpic']);
        }

        return array(
            'total' => $total,
            'list' => $list
        );
    }


    public function plan_where(): array
    {
        $list_sql = DB::select('id', 'chinesename', 'fieldname')
            ->from('customize_extend_field_desc')
            ->where('pid', '>', 0)
            ->execute()
            ->as_array();
        return $list_sql;
    }

    public function plan_more($params): array
    {
        extract($params);
        $customize_extend = [];
        //二级属性id
        if (!empty($attrid)) {
            $customize_extend = DB::select('p.fieldname', 'c.chinesename')
                ->from(array('customize_extend_field_desc', 'c'))
                ->join(array('customize_extend_field_desc', 'p'), 'left')
                ->on('p.id', '=', 'c.pid')
                ->where('c.id', '=', $attrid)
                ->execute()
                ->as_array();
            if (empty($customize_extend)) {
                return [];
            }
        }

        $list_sql = DB::select('cp.title', 'cp.id', 'cp.days', 'cp.litpic')
            ->from(array('customize_plan', 'cp'))
            ->join(array('customize_extend_field', 'cef'), 'left')
            ->on('cef.planid', '=', 'cp.id');
        if ($customize_extend) {
            foreach ($customize_extend as $index => $item) {
                $list_sql->where('cef.' . $item['fieldname'], '=', $item['chinesename']);
            }
        }
        if (!empty($keyword)) {
            $list_sql->where('cp.title', 'like', '%' . $keyword . '%');
        }
        $page = ($page - 1) * $pagesize;
        $list = $list_sql->offset($page)->limit($pagesize)
            ->execute()
            ->as_array();
        foreach ($list as $index2 => $item2) {
            $list[$index2]['litpic'] = Model_Api_V2_System::uniapp_img($item2['litpic']);
        }
        return $list;

    }

    public function plan_show($id): array
    {
        $info = DB::select()
            ->from('customize_plan')
            ->where('id', '=', $id)
            ->execute()
            ->current();

        if (!$info) {
            throw new Exception('计划不存在');
        }

        $info['extend_info'] = DB::select()
            ->from('customize_extend_field')
            ->where('planid', '=', $id)
            ->execute()
            ->current();

        $info['litpic']     = $this->img_url($info['litpic']);
        $info['piclist']    = $this->pic_list_url($info['piclist']);
        $attachment         = unserialize($info['linedoc']);
        $info['attachment'] = $attachment['path'][0] ? $this->img_url($attachment['path'][0]) : '';
        $info['content']    = $this->content_add_domain($info['content']);
        if($info['layout_method']==1){
            $info['trip_data']  = Model_Customize::handle_trip_data($info['trip_data'],true);
        }else{
            unset($info['trip_data']);
        }

        return $info;
    }

    public function extend_fields(): array
    {
        $extend_fields = Model_Customize_Extend_Field_Desc::get_fields();
        return array(
            'extend_fields' => $extend_fields,
            'contacttime' => array(
                '9:00-12:00', '14:00-18:00', '19:00-22:00'
            )
        );
    }

    public function add_order($params): array
    {
        if (!Model_Api_V2_Common::verify_image_code($params['captcha_key'], $params['code'])) {
            throw new Exception(__("checkcode_error"));
        }

        $mid = $params['mid'];

        $customize    = array(
            'addtime' => time(),
        );
        $extend_field = array();

        $filed = 'dest,starttime,startplace,days,adultnum,childnum,planerank,hotelrank,room,food,';
        $filed .= 'sex,address,phone,email,contacttime,addtime,contactname,content,viewstatus,memberid,';
        $filed .= 'title,linedoc,case_content,supplierlist,maxtpricejifen,budget';

        $filed_arr = explode(',', $filed);
        foreach ($params as $k => $v) {
            if (strpos($k, 'e_') === 0) {
                $extend_field[$k] = $v;
            } else {
                if (in_array($k, $filed_arr)) {
                    if ($k == 'adultnum' || $k == 'childnum') {
                        $v = $v ?: 0;
                    }
                    $customize[$k] = $v;
                }
            }
        }

        list($id, $rows) = DB::insert('customize', array_keys($customize))->values(array_values($customize))->execute();
        if (!$rows) {
            throw new Exception('下单失败');
        }

        $extend_field['productid'] = $id;
        list($extend_field_id, $extend_field_rows) = DB::insert('customize_extend_field', array_keys($extend_field))->values($extend_field)->execute();
        if (!$extend_field_rows) {
            throw new Exception('下单失败');
        }

        $order_sn = St_Product::get_ordersn(self::TYPE_ID);
        $order    = array(
            'ordersn' => $order_sn,
            'webid' => 0,
            'typeid' => self::TYPE_ID,
            'productautoid' => $id,
            'productaid' => 0,
            'productname' => '私人定制',
            'price' => 0,
            'usedate' => date('Y-m-d', $params['starttime']),
            'dingnum' => 1,
            'departdate' => '',
            'linkman' => $customize['contactname'],
            'linktel' => $customize['phone'],
            'linkemail' => $customize['email'],
            'jifentprice' => 0,
            'jifenbook' => 0,
            'jifencomment' => 0,
            'addtime' => $customize['addtime'],
            'memberid' => $mid,
            'dingjin' => 0,
            'paytype' => 3,
            'suitid' => 0,
            'usejifen' => 0,
            'needjifen' => 0,
            'status' => 0,
            'isneedpiao' => 0
        );

        $result = Model_Api_V2_Order::add_order($order, 'Model_Customize');

        if (!$result['status']) {
            DB::delete('customize')->where('id', '=', $id)->execute();
            DB::delete('customize_extend_field')->where('productid', '=', $id)->execute();

            throw new Exception($result['msg']);
        }

        $order_info = Model_Member_Order::order_info($order['ordersn']);

        // 订单创建完成事件
        Hook::trigger('order_created', $order);

        // 返回订单信息
        $filter_keys = array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status');
        return $this->filter_data($filter_keys, $order_info);
    }

    public function show($product_id): array
    {
        $info                   = ORM::factory('customize', $product_id)->as_array();
        $info['linedoc']        = unserialize($info['linedoc']);
        $info['case_content']   = $this->content_add_domain($info['case_content']);
        $info['totalnum']       = bcadd($info['adultnum'], $info['childnum'], 0);
        $info['maxjifentprice'] = floor($info['maxtpricejifen'] / $GLOBALS['cfg_exchange_jifen']);
        $extend_info            = Model_Customize::get_extend_info($info['id']);
        $extend_fields          = Model_Customize_Extend_Field_Desc::get_fields();
        $arr                    = [];
        foreach ($extend_fields as $k => $v) {
            if (!empty($extend_info[$v['fieldname']])) {
                $arr[] = [
                    'field_name' => $v['chinesename'],
                    'field_val' => $extend_info[$v['fieldname']],
                ];
            }
        }
        foreach ($info['linedoc']['path'] as $key => $vel) {
            $info['linedoc']['path'][$key] = Model_Api_V2_System::reorganized_resource_url($vel);
        }
        $info['extend_info'] = $arr;
        if($info['layout_method']==1 && $info['trip_data']){
            $info['trip_data'] = Model_Customize::handle_trip_data($info['trip_data'],true);
            foreach ($info['trip_data'] as &$v) {
                $v['trip_content'] = $this->content_add_domain($v['trip_content']);
            }
        }else{
            $info['trip_data'] = [];
        }
        unset($info['memberid']);
        return $info;
    }

    public function get_max_use_jifen($params): array
    {
        $info = DB::select()
            ->from('customize')
            ->where('id', '=', $params['product_id'])
            ->execute()
            ->current();

        $cfg_exchange_jifen = DB::select()
            ->from('sysconfig')
            ->where('varname', '=', 'cfg_exchange_jifen')
            ->execute()
            ->get('value');

        $jifentprice = 0;
        if ($info['maxtpricejifen'] > 0 && $cfg_exchange_jifen > 0) {
            $jifentprice = floor($info['maxtpricejifen'] / $cfg_exchange_jifen);
        }

        return [
            'isopen' => $info['maxtpricejifen'] > 0 ? 1 : 0,
            'toplimit' => $info['maxtpricejifen'],
            'jifentprice' => $jifentprice,
            'cfg_exchange_jifen' => $cfg_exchange_jifen,
        ];
    }

    public function improve_order_info($params): array
    {
        $mid      = $params['mid'];
        $order_id = $params['order_id'];

        $order_model = ORM::factory('member_order')
            ->where('typeid', '=', self::TYPE_ID)
            ->where('memberid', '=', $mid)
            ->and_where('id', '=', $order_id)
            ->find();

        $order = $order_model->as_array();
        if (empty($order)) {
            throw new Exception('订单不存在');
        }

        //优惠券
        $coupon_id = Arr::get($params, 'coupon_id', '');
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $mid, $order);
            // 优惠券
            if (!empty($coupon_check)) {
                Model_Coupon::add_coupon_order($coupon_check['cid'], $order['ordersn'], $coupon_check['order_total_price'], $coupon_check, $coupon_id);
            }
        }

        //积分
        $use_jifen  = 0;
        $need_jifen = Arr::get($params, 'needjifen', '');
        if ($need_jifen && $order_model->usejifen != 1) {
            //$jifentprice = floor($need_jifen / $GLOBALS['cfg_exchange_jifen']);
            $jifentprice = bcdiv($need_jifen, $GLOBALS['cfg_exchange_jifen'], 2);
            if ($jifentprice > 0) {
                $use_jifen = 1;
            }
            $order_model->usejifen    = $use_jifen;
            $order_model->needjifen   = $need_jifen;
            $order_model->jifentprice = $jifentprice;
        }

        $order_model->remark = Arr::get($params, 'remark', '');
        $order_model->save();

        // 处理积分
        if ($order_model->usejifen && $order_model->needjifen) {
            Model_Member_Jifen::deduct($order_model->ordersn);
        }

        // 使用红包
        $envelope_member_id = Arr::get($params, 'envelope_member_id', 0);
        if ($envelope_member_id) {
            if (St_Functions::is_normal_app_install('red_envelope')) {
                Model_Order_Envelope::order_use_envelope($envelope_member_id, $order['ordersn'], self::TYPE_ID, $mid);
            }
        }

        $customize_model = new Model_Api_V2_Customize();

        // 添加游客
        $customize_model->del_order_tourist($order_id);
        $tourist = Arr::get($params, 'tourist', '');
        if ($tourist) {
            $tourist = json_decode($tourist, true);
            if (!empty($tourist)) {
                $customize_model->add_tourist($order['id'], $tourist);
            }
        }

        // 订单发票信息
        $customize_model->del_order_receipt($order_id);
        $receipt = Arr::get($params, 'receiptInfo', '');
        if ($receipt) {
            $receipt_info = json_decode($receipt, true);
            if (!empty($receipt_info)) {
                $customize_model->add_receipt($order['id'], $receipt_info);
            }
        }

        DB::update('customize')->set(['is_perfect'=>1])->where('id','=',$order['productautoid'])->execute();

        // 返回数据
        return $this->filter_data(array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status'), $order);
    }
}